<template>
  <div class="data-display-component">
    <!-- 组件头部控制区 -->
    <div class="display-controls">
      <div class="display-title-area">
        <div class="display-title" v-if="title">{{ title }}</div>
        <el-tag v-if="dataCount && showDataCount" size="small" effect="plain" round>
          {{ dataCount }} 条数据
        </el-tag>
      </div>
      <div class="display-actions">
        <el-tooltip content="刷新数据" placement="top" v-if="enableRefresh">
          <el-button circle size="small" @click="$emit('refresh-data')" :loading="loading">
            <el-icon><refresh /></el-icon>
          </el-button>
        </el-tooltip>

        <!-- 智能推荐模式选择器 -->
        <el-dropdown
          @command="handleModeChange"
          trigger="click"
          size="small"
          v-if="enableSmartRecommendation"
        >
          <el-button type="default" size="small">
            <el-icon><setting /></el-icon>
            显示模式 <el-icon class="el-icon--right"><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item
                v-for="rec in getAllRecommendations"
                :key="rec.mode"
                :command="rec.mode"
                :class="{ 'recommended-option': rec.confidence > 0.7 }"
              >
                <div class="mode-option">
                  <div class="mode-header">
                    <el-icon>
                      <grid v-if="rec.mode === 'table'" />
                      <pie-chart v-else-if="rec.mode === 'pie'" />
                      <histogram v-else-if="rec.mode === 'bar'" />
                      <trend-charts v-else-if="rec.mode === 'line'" />
                    </el-icon>
                    <span class="mode-name">{{ getModeDisplayName(rec.mode) }}</span>
                    <el-tag v-if="rec.confidence > 0.7" size="small" type="success" effect="plain">
                      推荐
                    </el-tag>
                  </div>
                  <div class="mode-reason">{{ rec.reason }}</div>
                </div>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>

        <!-- 传统模式选择器（作为备选） -->
        <el-select
          v-else
          v-model="currentDisplayMode"
          placeholder="选择显示模式"
          size="small"
          style="width: 100px"
        >
          <el-option label="表格" value="table">
            <el-icon class="option-icon"><grid /></el-icon> 表格
          </el-option>
          <el-option label="饼图" value="pie" :disabled="isForceTableMode">
            <el-icon class="option-icon"><pie-chart /></el-icon> 饼图
          </el-option>
          <el-option label="柱状图" value="bar" :disabled="isForceTableMode">
            <el-icon class="option-icon"><histogram /></el-icon> 柱状图
          </el-option>
          <el-option label="折线图" value="line" :disabled="isForceTableMode">
            <el-icon class="option-icon"><trend-charts /></el-icon> 折线图
          </el-option>
        </el-select>

        <!-- 添加配置按钮 -->
        <el-button
          v-if="enableCustomConfig && currentDisplayMode !== 'table'"
          type="default"
          size="small"
          style="width: 80px"
          plain
          @click="showChartConfig = !showChartConfig"
        >
          <el-icon><setting /></el-icon>
          配置
        </el-button>

        <!-- 添加导出按钮 -->
        <el-dropdown v-if="enableExport" @command="handleExport" trigger="click" size="small">
          <el-button type="default" plain size="small">
            导出 <el-icon class="el-icon--right"><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="csv">
                <el-icon><document /></el-icon> 导出CSV
              </el-dropdown-item>
              <el-dropdown-item command="excel" v-if="enableExcelExport">
                <el-icon><document /></el-icon> 导出Excel
              </el-dropdown-item>
              <el-dropdown-item command="image" v-if="currentDisplayMode !== 'table'">
                <el-icon><picture /></el-icon> 导出图片
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>

        <!-- 全屏按钮 -->
        <el-tooltip content="全屏显示" placement="top" v-if="enableFullscreen">
          <el-button circle size="small" @click="toggleFullscreen">
            <el-icon><full-screen /></el-icon>
          </el-button>
        </el-tooltip>
      </div>
    </div>

    <!-- 筛选区域 -->
    <div v-if="enableFilter && currentDisplayMode === 'table'" class="filter-container">
      <el-input
        v-model="filterText"
        placeholder="搜索..."
        clearable
        prefix-icon="search"
        size="small"
        style="width: 250px"
      ></el-input>
      <div class="filter-actions" v-if="showFilterActions">
        <el-button size="small" @click="$emit('advanced-filter')">高级筛选</el-button>
        <el-button size="small" type="danger" plain @click="filterText = ''">清除筛选</el-button>
      </div>
    </div>

    <!-- 图表配置区域 - 内嵌形式 -->
    <div v-if="showChartConfig && currentDisplayMode !== 'table'" class="inline-chart-config">
      <div class="chart-config-form">
        <div class="config-header">
          <h4>图表配置</h4>
          <el-button type="text" @click="showChartConfig = false">
            <el-icon><close /></el-icon>
          </el-button>
        </div>

        <el-tabs v-model="activeConfigTab">
          <el-tab-pane label="数据" name="data">
            <el-form label-position="top" size="small">
              <el-form-item label="图表类型">
                <el-radio-group v-model="currentDisplayMode">
                  <el-radio label="pie">饼图</el-radio>
                  <el-radio label="bar">柱状图</el-radio>
                  <el-radio label="line">折线图</el-radio>
                </el-radio-group>
              </el-form-item>

              <template v-if="currentDisplayMode !== 'table'">
                <el-form-item label="选择标签列">
                  <el-select v-model="userChartConfig.labelColumn" placeholder="选择标签列">
                    <el-option
                      v-for="column in dataAnalysis.all"
                      :key="column.prop"
                      :label="column.label"
                      :value="column.prop"
                    />
                  </el-select>
                </el-form-item>

                <el-form-item label="选择数值列" v-if="currentDisplayMode === 'pie'">
                  <el-select v-model="userChartConfig.valueColumn" placeholder="选择数值列">
                    <el-option
                      v-for="column in dataAnalysis.numeric"
                      :key="column.prop"
                      :label="column.label"
                      :value="column.prop"
                    />
                  </el-select>
                </el-form-item>

                <el-form-item label="选择要显示的数据系列" v-else>
                  <el-checkbox-group v-model="userChartConfig.selectedSeries">
                    <el-checkbox
                      v-for="column in dataAnalysis.numeric"
                      :key="column.prop"
                      :label="column.prop"
                    >
                      {{ column.label }}
                    </el-checkbox>
                  </el-checkbox-group>
                </el-form-item>

                <el-form-item label="数据排序" v-if="currentDisplayMode === 'pie'">
                  <el-radio-group v-model="userChartConfig.sortType">
                    <el-radio label="none">不排序</el-radio>
                    <el-radio label="asc">升序</el-radio>
                    <el-radio label="desc">降序</el-radio>
                  </el-radio-group>
                </el-form-item>

                <el-form-item label="显示数据标签" v-if="currentDisplayMode !== 'table'">
                  <el-switch v-model="userChartConfig.showDataLabels"></el-switch>
                </el-form-item>
              </template>
            </el-form>
          </el-tab-pane>

          <el-tab-pane label="样式" name="style">
            <el-form label-position="top" size="small">
              <el-form-item label="主题色">
                <el-color-picker v-model="userChartConfig.themeColor"></el-color-picker>
              </el-form-item>

              <el-form-item label="显示图例">
                <el-switch v-model="userChartConfig.showLegend"></el-switch>
              </el-form-item>

              <el-form-item label="图例位置" v-if="userChartConfig.showLegend">
                <el-select v-model="userChartConfig.legendPosition">
                  <el-option label="顶部" value="top" />
                  <el-option label="底部" value="bottom" />
                  <el-option label="左侧" value="left" />
                  <el-option label="右侧" value="right" />
                </el-select>
              </el-form-item>

              <el-form-item label="背景色">
                <el-color-picker
                  v-model="userChartConfig.backgroundColor"
                  show-alpha
                ></el-color-picker>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>

        <div class="chart-actions">
          <el-button type="primary" @click="applyChartConfig">应用配置</el-button>
          <el-button @click="resetChartConfig">重置配置</el-button>
          <el-button @click="closeChartConfig">关闭配置</el-button>
          <el-button @click="saveAsTemplate" v-if="enableTemplates">保存为模板</el-button>
        </div>
      </div>
    </div>

    <!-- 表格展示区域 -->
    <div v-show="currentDisplayMode === 'table'" class="table-container">
      <el-table
        :data="displayData"
        border
        stripe
        style="width: 100%"
        :max-height="maxHeight"
        v-loading="loading"
        @sort-change="handleSortChange"
        @row-click="onRowClick"
        :default-sort="defaultSort"
        highlight-current-row
      >
        <el-table-column
          v-for="column in columns"
          :key="column.prop"
          :prop="column.prop"
          :label="column.label"
          :width="column.width"
          :sortable="column.sortable"
          :formatter="column.formatter"
          :show-overflow-tooltip="column.showOverflowTooltip || true"
        >
          <template #default="scope" v-if="column.slotName">
            <slot :name="column.slotName" :row="scope.row" :column="column"></slot>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <div class="pagination-container" v-if="enablePagination && filteredTableData.length > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredTableData.length"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 图表展示区域 -->
    <div v-show="currentDisplayMode !== 'table'" class="chart-container" :style="chartStyle">
      <div ref="chartRef" style="width: 100%; height: 450px"></div>
      <div v-if="!hasData" class="no-data">
        <el-empty description="没有可用数据" :image-size="60"></el-empty>
      </div>

      <!-- 图表加载状态 -->
      <div v-if="loading" class="chart-loading">
        <el-loading />
      </div>
    </div>

    <!-- 模板选择对话框 -->
    <el-dialog v-model="showTemplateDialog" title="保存图表模板" width="30%">
      <el-form :model="templateForm" label-position="top">
        <el-form-item label="模板名称">
          <el-input v-model="templateForm.name" placeholder="请输入模板名称"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="templateForm.description"
            type="textarea"
            placeholder="请输入模板描述"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showTemplateDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmSaveTemplate">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 全屏容器 -->
    <div ref="fullscreenContainer" class="fullscreen-container"></div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, nextTick, onUnmounted } from 'vue'
import * as echarts from 'echarts' // 使用 ECharts 5.2.0 版本
import {
  ArrowDown,
  Setting,
  Refresh,
  Grid,
  PieChart,
  Histogram,
  TrendCharts,
  Document,
  FullScreen,
  Close,
} from '@element-plus/icons-vue'
import * as XLSX from 'xlsx'

// 接收的prop属性
const props = defineProps({
  // 数据源
  data: {
    type: Array,
    default: () => [],
  },
  // 表格列配置
  columns: {
    type: Array,
    default: () => [],
  },
  // 图表配置参数
  chartOptions: {
    type: Object,
    default: () => ({}),
  },
  // 标题
  title: {
    type: String,
    default: '',
  },
  // 默认显示模式
  defaultMode: {
    type: String,
    default: 'auto',
  },
  // 表格最大高度
  maxHeight: {
    type: [String, Number],
    default: '400px',
  },
  // 图表高度
  chartHeight: {
    type: [String, Number],
    default: '400px',
  },
  // 加载状态
  loading: {
    type: Boolean,
    default: false,
  },
  // 是否启用导出功能
  enableExport: {
    type: Boolean,
    default: true,
  },
  // 是否允许用户自定义图表配置
  enableCustomConfig: {
    type: Boolean,
    default: true,
  },
  // 是否启用Excel导出
  enableExcelExport: {
    type: Boolean,
    default: false,
  },
  // 是否启用全屏
  enableFullscreen: {
    type: Boolean,
    default: false,
  },
  // 是否显示数据条数
  showDataCount: {
    type: Boolean,
    default: true,
  },
  // 是否启用刷新
  enableRefresh: {
    type: Boolean,
    default: false,
  },
  // 是否启用筛选
  enableFilter: {
    type: Boolean,
    default: false,
  },
  // 是否显示筛选操作
  showFilterActions: {
    type: Boolean,
    default: false,
  },
  // 是否启用分页
  enablePagination: {
    type: Boolean,
    default: false,
  },
  // 是否启用模板保存功能
  enableTemplates: {
    type: Boolean,
    default: false,
  },
  // 默认排序
  defaultSort: {
    type: Object,
    default: () => ({}),
  },
  // 是否启用智能推荐
  enableSmartRecommendation: {
    type: Boolean,
    default: true,
  },
})

// 用于与父组件通信的事件
const emit = defineEmits([
  'chart-mode-change',
  'export-data',
  'refresh-data',
  'advanced-filter',
  'sort-change',
  'page-change',
  'template-save',
  'row-click',
])

// 数据处理与状态管理
const tableData = computed(() => props.data || [])
const dataCount = computed(() => tableData.value.length)
const hasData = computed(() => tableData.value && tableData.value.length > 0)

// 初始化显示模式 - 如果是auto模式，将在数据分析完成后设置
const currentDisplayMode = ref(props.defaultMode === 'auto' ? 'table' : props.defaultMode)

// 检查是否应该强制使用表格模式
const isForceTableMode = computed(() => {
  return hasData.value && tableData.value.length > 100
})

const chartRef = ref(null)
// 将 chartInstance 从响应式变量改为普通变量，避免 Vue 3 响应式系统干扰 ECharts 访问内部属性
let chartInstance = null // 改为普通变量，而非响应式引用
const showChartConfig = ref(false)
const filterText = ref('')
const activeConfigTab = ref('data')
const currentPage = ref(1)
const pageSize = ref(20)
const fullscreenContainer = ref(null)
const isFullscreen = ref(false)
const showTemplateDialog = ref(false)
const templateForm = ref({
  name: '',
  description: '',
})

// 用户自定义图表配置
const userChartConfig = ref({
  labelColumn: '',
  valueColumn: '',
  selectedSeries: [],
  sortType: 'none',
  showDataLabels: true,
  showLegend: true,
  legendPosition: 'bottom',
  themeColor: '#409EFF',
  backgroundColor: 'rgba(255, 255, 255, 0)',
})

// 筛选后的表格数据
const filteredTableData = computed(() => {
  if (!filterText.value) return tableData.value

  const searchText = filterText.value.toLowerCase()
  return tableData.value.filter((row) => {
    return props.columns.some((column) => {
      const value = row[column.prop]
      if (value === null || value === undefined) return false
      return String(value).toLowerCase().includes(searchText)
    })
  })
})

// 获取要显示的表格数据（包含分页）
const displayData = computed(() => {
  if (!props.enablePagination) return filteredTableData.value

  const startIndex = (currentPage.value - 1) * pageSize.value
  const endIndex = startIndex + pageSize.value
  return filteredTableData.value.slice(startIndex, endIndex)
})

// 自动分析数据结构
const dataAnalysis = computed(() => {
  if (!hasData.value) return { numeric: [], text: [], date: [], boolean: [], all: [] }

  const result = {
    numeric: [], // 存储数值型列
    text: [], // 存储文本型列
    date: [], // 存储日期型列
    boolean: [], // 存储布尔型列
    all: [], // 存储所有列
  }

  // 获取所有列属性
  const allProps = new Set()
  tableData.value.forEach((row) => {
    Object.keys(row).forEach((key) => allProps.add(key))
  })

  // 分析每列的数据类型
  allProps.forEach((prop) => {
    // 查找列配置信息
    const columnConfig = props.columns.find((col) => col.prop === prop) || { prop, label: prop }
    const samples = tableData.value
      .map((row) => row[prop])
      .filter((v) => v !== undefined && v !== null)

    if (samples.length === 0) {
      result.text.push({ ...columnConfig, dataType: 'text' })
      return
    }

    // 判断数据类型
    let isNumeric = true
    let isBoolean = true
    let isDate = true

    for (const sample of samples) {
      // 检查是否为数值
      const numValue = parseFloat(sample)
      if (isNaN(numValue) || sample === true || sample === false) {
        isNumeric = false
      }

      // 检查是否为布尔值
      if (
        sample !== true &&
        sample !== false &&
        sample !== 'true' &&
        sample !== 'false' &&
        sample !== 1 &&
        sample !== 0 &&
        sample !== '1' &&
        sample !== '0'
      ) {
        isBoolean = false
      }

      // 检查是否为日期 (简单检查，可以扩展)
      if (!(sample instanceof Date) && isNaN(new Date(sample).getTime())) {
        isDate = false
      }
    }

    const colInfo = { ...columnConfig, dataType: 'text' }

    if (isNumeric) {
      colInfo.dataType = 'numeric'
      result.numeric.push(colInfo)
    } else if (isBoolean) {
      colInfo.dataType = 'boolean'
      result.boolean.push(colInfo)
    } else if (isDate) {
      colInfo.dataType = 'date'
      result.date.push(colInfo)
    } else {
      result.text.push(colInfo)
    }

    result.all.push(colInfo)
  })

  return result
})

// 初始化用户配置函数
const initUserConfig = () => {
  const analysis = dataAnalysis.value
  if (!analysis || !analysis.all || analysis.all.length === 0) {
    return // 如果还没有数据分析结果，则不进行初始化
  }

  // 默认选择第一个文本或日期列作为标签
  let labelColumn = null
  if (analysis.text && analysis.text.length > 0) {
    labelColumn = analysis.text[0]
  } else if (analysis.date && analysis.date.length > 0) {
    labelColumn = analysis.date[0]
  } else if (analysis.all.length > 0) {
    labelColumn = analysis.all[0]
  }

  if (labelColumn) {
    userChartConfig.value.labelColumn = labelColumn.prop
  }

  // 默认选择第一个数值列作为值
  if (analysis.numeric && analysis.numeric.length > 0) {
    userChartConfig.value.valueColumn = analysis.numeric[0].prop

    // 对于非饼图，默认选择所有数值列
    userChartConfig.value.selectedSeries = analysis.numeric.map((col) => col.prop)
  }

  // 设置其他默认值
  userChartConfig.value.sortType = 'none'
  userChartConfig.value.showDataLabels = true
  userChartConfig.value.showLegend = true
  userChartConfig.value.legendPosition = 'bottom'
  userChartConfig.value.themeColor = '#409EFF'
  userChartConfig.value.backgroundColor = 'rgba(255, 255, 255, 0)'
}

// 观察模式变化，触发事件
watch(currentDisplayMode, (newMode) => {
  // 触发模式变更事件
  emit('chart-mode-change', newMode)
  // 重置分页
  currentPage.value = 1

  // 自动调整配置项以匹配当前模式
  if (newMode !== 'table' && hasData.value) {
    console.log('模式切换为:', newMode)
    nextTick(() => {
      try {
        // 如果从表格切换到其他模式，且配置为空，需要初始化配置
        if (!userChartConfig.value.labelColumn || userChartConfig.value.labelColumn === '') {
          console.log('初始化图表配置')
          initUserConfig()
        }

        // 检查DOM元素
        console.log('图表DOM元素状态:', chartRef.value, chartRef.value?.offsetHeight)

        // 创建对应的图表
        setTimeout(() => {
          console.log('延迟创建图表')
          createChart()
        }, 100)
      } catch (err) {
        console.error('模式切换时创建图表失败:', err)
      }
    })
  }
})

// 监听数据分析结果变化，初始化用户配置
watch(
  dataAnalysis,
  (analysis) => {
    // 确保分析结果有效
    if (!analysis || !analysis.all || analysis.all.length === 0) {
      return
    }

    // 如果没有明确指定默认模式，使用智能推荐
    if (!props.defaultMode || props.defaultMode === 'auto') {
      const recommendation = getRecommendedDisplayMode.value
      if (recommendation && recommendation.mode !== currentDisplayMode.value) {
        currentDisplayMode.value = recommendation.mode
      }
    }

    // 只在首次分析后初始化或者当前配置无效时初始化
    const configIsValid =
      userChartConfig.value.labelColumn &&
      analysis.all.some((col) => col.prop === userChartConfig.value.labelColumn)

    if (!configIsValid) {
      initUserConfig()
    }
  },
  { immediate: false },
) // 设置为false，避免立即执行

// 监听数据变化重绘图表
watch(
  () => props.data,
  (newData) => {
    // 重置分页
    currentPage.value = 1

    // 只有当数据从空变为有值时才执行初始化
    if (newData && newData.length > 0 && !userChartConfig.value.labelColumn) {
      nextTick(() => {
        initUserConfig()
      })
    }

    // 重绘图表
    if (currentDisplayMode.value !== 'table' && newData && newData.length > 0) {
      nextTick(() => {
        try {
          createChart()
        } catch (err) {
          console.error('数据变化时创建图表失败:', err)
        }
      })
    }
  },
  { immediate: true, deep: true },
)

// 监听窗口颜色模式变化
watch(
  () => document.documentElement.classList.contains('dark-mode'),
  (isDarkMode) => {
    // 当颜色模式变化时重绘图表
    if (currentDisplayMode.value !== 'table' && hasData.value) {
      nextTick(() => {
        console.log('主题模式变化，重绘图表', isDarkMode ? 'dark' : 'light')
        createChart()
      })
    }
  },
  { immediate: false },
)

// 智能推荐最佳展示模式
const getRecommendedDisplayMode = computed(() => {
  if (!hasData.value) return { mode: 'table', confidence: 0, reason: '无数据' }

  const analysis = dataAnalysis.value
  const rowCount = tableData.value.length

  // 推荐规则系统
  const recommendations = []

  // 规则-1: 数据量超过100条时强制使用表格展示（最高优先级）
  if (rowCount > 100) {
    recommendations.push({
      mode: 'table',
      confidence: 1.0, // 最高置信度，确保强制使用
      reason: `数据量超过100条(${rowCount}行)，强制使用表格展示以确保性能和用户体验`,
    })
  }

  // 规则0: 列数超过5列且第3列后存在非数字列时优先推荐表格
  if (analysis.all.length > 5) {
    // 检查第3列后是否存在非数字列
    const columnsAfterThird = analysis.all.slice(2) // 从第3列开始（索引2）
    const hasNonNumericAfterThird = columnsAfterThird.some(
      (col) =>
        col.dataType !== 'numeric' && !analysis.numeric.some((numCol) => numCol.prop === col.prop),
    )

    if (hasNonNumericAfterThird) {
      recommendations.push({
        mode: 'table',
        confidence: 0.95,
        reason: `数据结构复杂(${analysis.all.length}列，第3列后含非数字列)，表格展示更清晰`,
      })
    }
  }

  // 规则1: 数据量很大时推荐表格
  if (rowCount > 500) {
    recommendations.push({
      mode: 'table',
      confidence: 0.9,
      reason: `数据量较大(${rowCount}行)，表格展示更适合浏览和搜索`,
    })
  }

  // 规则2: 饼图推荐规则 - 只有在数据量不超过100条时才推荐
  if (
    analysis.text.length >= 1 &&
    analysis.numeric.length >= 1 &&
    rowCount <= 20 &&
    rowCount <= 100
  ) {
    // 检查数值分布是否适合饼图
    const firstNumericCol = analysis.numeric[0]
    const values = tableData.value
      .map((row) => parseFloat(row[firstNumericCol.prop]))
      .filter((v) => !isNaN(v))
    const total = values.reduce((sum, v) => sum + v, 0)
    const hasPositiveValues = values.every((v) => v >= 0)

    if (hasPositiveValues && total > 0) {
      recommendations.push({
        mode: 'pie',
        confidence: 0.8,
        reason: `${rowCount}个分类，数值均为正数，适合展示占比关系`,
      })
    }
  }

  // 规则3: 时间序列数据推荐折线图 - 只有在数据量不超过100条时才推荐
  if (analysis.date.length >= 1 && analysis.numeric.length >= 1 && rowCount <= 100) {
    recommendations.push({
      mode: 'line',
      confidence: 0.9,
      reason: '包含时间字段，适合展示趋势变化',
    })
  }

  // 规则4: 分类对比推荐柱状图 - 只有在数据量不超过100条时才推荐
  if (
    analysis.text.length >= 1 &&
    analysis.numeric.length >= 1 &&
    rowCount <= 50 &&
    rowCount <= 100
  ) {
    recommendations.push({
      mode: 'bar',
      confidence: 0.7,
      reason: `${rowCount}个分类，适合对比数值大小`,
    })
  }

  // 规则5: 多数值列推荐柱状图或折线图 - 只有在数据量不超过100条时才推荐
  if (analysis.numeric.length > 2 && rowCount <= 100) {
    if (analysis.date.length > 0 || analysis.text.length > 0) {
      recommendations.push({
        mode: 'bar',
        confidence: 0.6,
        reason: `多个数值字段(${analysis.numeric.length}个)，适合多维度对比`,
      })
    }
  }

  // 规则6: 默认表格
  recommendations.push({
    mode: 'table',
    confidence: 0.5,
    reason: '表格是通用的数据展示方式',
  })

  // 选择置信度最高的推荐
  const bestRecommendation = recommendations.reduce((best, current) =>
    current.confidence > best.confidence ? current : best,
  )

  return bestRecommendation
})

// 获取所有推荐选项（用于显示给用户）
const getAllRecommendations = computed(() => {
  if (!hasData.value) return []

  const analysis = dataAnalysis.value
  const rowCount = tableData.value.length
  const recommendations = []

  // 数据量超过100条时，强制只显示表格选项
  if (rowCount > 100) {
    recommendations.push({
      mode: 'table',
      confidence: 1.0,
      reason: `数据量超过100条(${rowCount}行)，强制使用表格展示以确保性能和用户体验`,
      icon: 'Grid',
    })
    return recommendations // 直接返回，不提供其他选项
  }

  // 检查是否满足优先表格显示的条件
  let tableReason = rowCount > 100 ? '大量数据，支持搜索和排序' : '原始数据查看'
  let tableConfidence = rowCount > 100 ? 0.9 : 0.6

  // 规则：列数超过5列且第3列后存在非数字列时优先推荐表格
  if (analysis.all.length > 5) {
    const columnsAfterThird = analysis.all.slice(2) // 从第3列开始（索引2）
    const hasNonNumericAfterThird = columnsAfterThird.some(
      (col) =>
        col.dataType !== 'numeric' && !analysis.numeric.some((numCol) => numCol.prop === col.prop),
    )

    if (hasNonNumericAfterThird) {
      tableConfidence = 0.95
      tableReason = `数据结构复杂(${analysis.all.length}列，第3列后含非数字列)，表格展示更清晰`
    }
  }

  // 表格推荐
  recommendations.push({
    mode: 'table',
    confidence: tableConfidence,
    reason: tableReason,
    icon: 'Grid',
  })

  // 只有在数据量不超过100条时才提供其他展示选项
  if (rowCount <= 100) {
  // 饼图推荐
  if (analysis.text.length >= 1 && analysis.numeric.length >= 1 && rowCount <= 20) {
    const firstNumericCol = analysis.numeric[0]
    const values = tableData.value
      .map((row) => parseFloat(row[firstNumericCol.prop]))
      .filter((v) => !isNaN(v))
    const hasPositiveValues = values.every((v) => v >= 0)

    if (hasPositiveValues) {
      recommendations.push({
        mode: 'pie',
        confidence: 0.8,
        reason: '展示各部分占比关系',
        icon: 'PieChart',
      })
    }
  }

  // 折线图推荐
  if (analysis.date.length >= 1 && analysis.numeric.length >= 1) {
    recommendations.push({
      mode: 'line',
      confidence: 0.9,
      reason: '时间序列趋势分析',
      icon: 'TrendCharts',
    })
  }

  // 柱状图推荐
  if (analysis.text.length >= 1 && analysis.numeric.length >= 1 && rowCount <= 100) {
    recommendations.push({
      mode: 'bar',
      confidence: analysis.numeric.length > 1 ? 0.8 : 0.7,
      reason: analysis.numeric.length > 1 ? '多维度数据对比' : '分类数据对比',
      icon: 'Histogram',
    })
    }
  }

  return recommendations.sort((a, b) => b.confidence - a.confidence)
})

// 智能选择标签列和数据列
const chartConfig = computed(() => {
  const analysis = dataAnalysis.value

  // 默认配置
  const config = {
    labelColumn: null,
    valueColumns: [],
    labelColumnIndex: 0,
    mode: currentDisplayMode.value,
  }

  // 如果用户有自定义配置，优先使用用户配置
  if (userChartConfig.value.labelColumn) {
    const labelCol = analysis.all.find((col) => col.prop === userChartConfig.value.labelColumn)
    if (labelCol) {
      config.labelColumn = labelCol
    }

    // 饼图只使用一个值列
    if (currentDisplayMode.value === 'pie' && userChartConfig.value.valueColumn) {
      const valueCol = analysis.numeric.find(
        (col) => col.prop === userChartConfig.value.valueColumn,
      )
      if (valueCol) {
        config.valueColumns = [valueCol]
      }
    }
    // 柱状图和折线图可以使用多个值列
    else if (
      (currentDisplayMode.value === 'bar' || currentDisplayMode.value === 'line') &&
      userChartConfig.value.selectedSeries &&
      userChartConfig.value.selectedSeries.length > 0
    ) {
      const selectedCols = analysis.numeric.filter((col) =>
        userChartConfig.value.selectedSeries.includes(col.prop),
      )
      if (selectedCols.length > 0) {
        config.valueColumns = selectedCols
      }
    }

    // 如果用户配置有效，直接返回
    if (config.labelColumn && config.valueColumns.length > 0) {
      // 获取标签列索引
      const index = analysis.all.findIndex((col) => col.prop === config.labelColumn.prop)
      if (index !== -1) {
        config.labelColumnIndex = index
      }
      return config
    }
  }

  // 用户配置无效，使用自动分析的结果
  // 根据图表类型选择合适的列
  if (currentDisplayMode.value === 'pie') {
    // 饼图需要一个文本列作为标签，一个数值列作为值
    if (analysis.text.length > 0 && analysis.numeric.length > 0) {
      config.labelColumn = analysis.text[0]
      config.valueColumns = [analysis.numeric[0]]
    }
    // 如果没有文本列，使用第一个列作为标签
    else if (analysis.numeric.length > 1) {
      config.labelColumn = analysis.all[0]
      config.valueColumns = [analysis.numeric[0]]
    }
    // 如果只有一个数值列，创建序号标签
    else if (analysis.numeric.length === 1) {
      config.labelColumn = { prop: '_index', label: '序号', dataType: 'text' }
      config.valueColumns = [analysis.numeric[0]]
    }
  }
  // 折线图和柱状图
  else if (currentDisplayMode.value === 'line' || currentDisplayMode.value === 'bar') {
    // 如果有日期列，优先使用日期列作为X轴
    if (analysis.date.length > 0 && analysis.numeric.length > 0) {
      config.labelColumn = analysis.date[0]
      config.valueColumns = analysis.numeric
    }
    // 如果有文本列，使用第一个文本列作为X轴
    else if (analysis.text.length > 0 && analysis.numeric.length > 0) {
      config.labelColumn = analysis.text[0]
      config.valueColumns = analysis.numeric
    }
    // 如果都是数值列，使用第一个作为X轴
    else if (analysis.numeric.length > 1) {
      config.labelColumn = analysis.numeric[0]
      config.valueColumns = analysis.numeric.slice(1)
    }
    // 如果只有一个数值列，创建序号标签
    else if (analysis.numeric.length === 1) {
      config.labelColumn = { prop: '_index', label: '序号', dataType: 'text' }
      config.valueColumns = analysis.numeric
    }
  }

  // 获取标签列索引，用于调整数据处理方式
  if (config.labelColumn && config.labelColumn.prop !== '_index') {
    const index = analysis.all.findIndex((col) => col.prop === config.labelColumn.prop)
    if (index !== -1) {
      config.labelColumnIndex = index
    }
  }

  return config
})

// 图表样式
const chartStyle = computed(() => {
  return {
    height: typeof props.chartHeight === 'number' ? `${props.chartHeight}px` : props.chartHeight,
    position: 'relative',
    minHeight: '500px',
  }
})

// 处理表格排序变化
const handleSortChange = (sortParams) => {
  emit('sort-change', sortParams)
}

// 处理分页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size
  emit('page-change', { page: currentPage.value, pageSize: size })
}

// 处理当前页变化
const handleCurrentChange = (page) => {
  currentPage.value = page
  emit('page-change', { page, pageSize: pageSize.value })
}

// 全屏切换
const toggleFullscreen = () => {
  if (!isFullscreen.value) {
    // 进入全屏
    const element = document.documentElement
    if (element.requestFullscreen) {
      element.requestFullscreen()
    } else if (element.mozRequestFullScreen) {
      element.mozRequestFullScreen()
    } else if (element.webkitRequestFullscreen) {
      element.webkitRequestFullscreen()
    } else if (element.msRequestFullscreen) {
      element.msRequestFullscreen()
    }
    isFullscreen.value = true
  } else {
    // 退出全屏
    if (document.exitFullscreen) {
      document.exitFullscreen()
    } else if (document.mozCancelFullScreen) {
      document.mozCancelFullScreen()
    } else if (document.webkitExitFullscreen) {
      document.webkitExitFullscreen()
    } else if (document.msExitFullscreen) {
      document.msExitFullscreen()
    }
    isFullscreen.value = false
  }
}

// 从主题色获取颜色
const getColorFromTheme = (index) => {
  const baseColor = userChartConfig.value.themeColor || '#409EFF'

  // 为了简化，这里使用预定义的颜色数组
  const colors = [
    baseColor,
    'rgba(255, 99, 132, 0.7)',
    'rgba(255, 206, 86, 0.7)',
    'rgba(75, 192, 192, 0.7)',
    'rgba(153, 102, 255, 0.7)',
    'rgba(255, 159, 64, 0.7)',
    'rgba(199, 199, 199, 0.7)',
    'rgba(83, 102, 255, 0.7)',
    'rgba(40, 159, 64, 0.7)',
    'rgba(210, 199, 199, 0.7)',
  ]

  return colors[index % colors.length]
}

// 创建图表
const createChart = () => {
  if (!chartRef.value) return

  // 如果没有数据，不创建图表
  if (!hasData.value) {
    console.log('没有数据，不创建图表')
    return
  }

  // 确保DOM已渲染
  nextTick(() => {
    try {
      // 移除之前的事件监听（如果有）
      if (handleResize.current) {
        window.removeEventListener('resize', handleResize.current)
      }

      // 销毁之前的图表实例
      if (chartInstance) {
        chartInstance.dispose()
      }

      console.log('正在初始化图表', chartRef.value)

      // 判断是否是暗黑模式
      const isDarkMode = document.documentElement.classList.contains('dark')

      // 初始化图表 - ECharts 5.2.0 初始化方式
      chartInstance = echarts.init(chartRef.value, {
        renderer: 'canvas', // canvas性能更好
        useDirtyRect: true, // 优化渲染性能
        devicePixelRatio: window.devicePixelRatio, // 适配高DPI设备
        darkMode: isDarkMode, // 暗黑模式
      })

      // 准备配置
      const option = getChartOption()

      // 暗黑模式下调整文字颜色
      if (isDarkMode) {
        // 调整标题颜色
        if (option.title) {
          option.title.textStyle = {
            color: '#E5EAF3',
          }
        }

        // 调整坐标轴颜色
        if (option.xAxis) {
          option.xAxis.axisLabel = {
            ...option.xAxis.axisLabel,
            color: '#E5EAF3',
          }
        }

        if (option.yAxis) {
          option.yAxis.axisLabel = {
            ...option.yAxis.axisLabel,
            color: '#E5EAF3',
          }
        }

        // 如果已有提示框配置，则扩展而不是覆盖
        if (option.tooltip) {
          option.tooltip = {
            ...option.tooltip,
            textStyle: {
              ...option.tooltip.textStyle,
              color: '#E5EAF3',
            },
            backgroundColor: 'rgba(50, 50, 50, 0.9)',
            borderColor: 'rgba(70, 70, 70, 0.9)',
          }
        }
      }

      console.log('图表配置:', option)

      // 设置配置
      chartInstance.setOption(option)

      // 保存对图表实例的引用，避免闭包中使用可能发生变化的变量
      const myChart = chartInstance

      // 添加图例点击事件拦截
      chartInstance.on('legendselectchanged', function (params) {
        try {
          // 图例点击事件的安全处理
          if (!params || !params.selected) return
          console.log('Legend selected change:', params)

          // 手动更新选中状态并重新渲染图表
          const selected = params.selected
          setTimeout(() => {
            // 使用保存的引用而不是可能变化的chartInstance
            if (myChart && !myChart.isDisposed()) {
              myChart.setOption({
                legend: { selected },
              })
            }
          }, 0)
        } catch (error) {
          console.error('图例点击事件处理错误:', error)
        }
      })

      // 添加交互事件处理
      chartInstance.on('click', function (params) {
        console.log('点击图表元素:', params)
        // 可以在这里添加点击处理逻辑
      })

      // 创建一个针对当前图表实例的resize处理函数
      const resizeHandler = () => {
        if (myChart && !myChart.isDisposed()) {
          myChart.resize({ animation: { duration: 300 } })
        }
      }

      // 保存当前的resize处理函数引用
      handleResize.current = resizeHandler

      // 注册窗口大小变化事件，使用当前实例的特定处理函数
      window.addEventListener('resize', resizeHandler)
    } catch (err) {
      console.error('创建图表失败:', err)
    }
  })
}

// 重置大小处理对象
const handleResize = {
  current: null,
}

// 获取图表配置
const getChartOption = () => {
  if (!hasData.value) {
    return { title: { text: '无数据', left: 'center', top: 'center' } }
  }

  const config = chartConfig.value

  // 准备配置
  let option = {
    backgroundColor: userChartConfig.value.backgroundColor || 'transparent',
    // 启用动画效果
    animation: true,
    animationDuration: 1000,
    animationEasing: 'cubicOut',
    animationThreshold: 2000, // 最多有2000个数据点时显示动画
    // 动画延迟
    animationDelay: function (idx) {
      // 延迟随索引增加而增加
      return idx * 20
    },
    // 动画阈值
    progressiveThreshold: 3000,
    progressive: 200,
    // 通用配置
    legend: {
      type: 'scroll', // 使用带滚动的图例
      selectedMode: 'multiple', // 允许多选
      animation: true, // 启用图例动画
    },
    // 添加工具提示过渡动画
    tooltip: {
      trigger: 'item',
      transitionDuration: 0.4, // 过渡动画时长
      formatter: '{a} <br/>{b}: {c}',
      backgroundColor: 'rgba(50, 50, 50, 0.7)',
      borderColor: 'rgba(70, 70, 70, 0.7)',
      textStyle: {
        color: '#fff',
      },
    },
  }

  // 添加标题
  if (props.title) {
    option.title = {
      text: props.title,
      left: 'center',
    }
  }

  // 根据图表类型构建特定配置
  if (currentDisplayMode.value === 'pie') {
    return buildPieChartOption(option, config)
  } else if (currentDisplayMode.value === 'bar') {
    return buildBarChartOption(option, config)
  } else if (currentDisplayMode.value === 'line') {
    return buildLineChartOption(option, config)
  }

  return option
}

// 构建饼图配置
const buildPieChartOption = (baseOption, config) => {
  // 获取值列
  const valueColumn = config.valueColumns[0]?.prop
  if (!valueColumn) return baseOption

  // 饼图特殊处理 - 需要将数据预先加工为适合饼图显示的格式
  const labelColumn = config.labelColumn?.prop || '_index'
  const pieData = []

  // 准备饼图数据
  tableData.value.forEach((item, index) => {
    const label =
      labelColumn === '_index' ? `项目${index + 1}` : item[labelColumn] || `项目${index + 1}`
    const value = parseFloat(item[valueColumn])
    if (!isNaN(value)) {
      pieData.push({
        name: label,
        value: value,
      })
    }
  })

  // 应用排序
  if (userChartConfig.value.sortType === 'asc') {
    pieData.sort((a, b) => a.value - b.value)
  } else if (userChartConfig.value.sortType === 'desc') {
    pieData.sort((a, b) => b.value - a.value)
  }

  // 初始化图例选中状态
  const legendSelected = {}
  pieData.forEach((item) => {
    legendSelected[item.name] = true
  })

  // 构建饼图配置
  const option = {
    ...baseOption,
    tooltip: {
      ...baseOption.tooltip,
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)',
    },
    legend: {
      ...baseOption.legend,
      show: userChartConfig.value.showLegend,
      orient:
        userChartConfig.value.legendPosition === 'left' ||
        userChartConfig.value.legendPosition === 'right'
          ? 'vertical'
          : 'horizontal',
      left:
        userChartConfig.value.legendPosition === 'right'
          ? 'right'
          : userChartConfig.value.legendPosition === 'left'
            ? 'left'
            : 'center',
      top: userChartConfig.value.legendPosition === 'bottom' ? 'bottom' : 'top',
      selected: legendSelected,
    },
    series: [
      {
        name: valueColumn,
        type: 'pie',
        radius: ['35%', '70%'], // 改为环形图，更现代的外观
        center: ['50%', '50%'],
        avoidLabelOverlap: true,
        itemStyle: {
          borderRadius: 10, // 添加圆角效果
          borderColor: '#fff',
          borderWidth: 2,
        },
        label: {
          show: userChartConfig.value.showDataLabels,
          formatter: '{b}: {d}%',
          position: 'outside',
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '16',
            fontWeight: 'bold',
          },
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          },
          scale: true, // 高亮时放大
          scaleSize: 10, // 放大尺寸
        },
        labelLine: {
          show: userChartConfig.value.showDataLabels,
          length: 10, // 第一段线长
          length2: 15, // 第二段线长
          smooth: true, // 平滑的标签引导线
        },
        data: pieData,
        color: pieData.map((_, i) => getColorFromTheme(i)),
        animationType: 'scale', // 缩放动画
        animationEasing: 'elasticOut', // 弹性缓动动画
        animationDelay: function (idx) {
          return idx * 60 // 根据索引添加更长的延迟
        },
      },
    ],
  }

  return option
}

// 构建柱状图配置
const buildBarChartOption = (baseOption, config) => {
  // 柱状图配置
  const labelColumn = config.labelColumn?.prop
  if (!labelColumn) return baseOption

  // 获取所有类别 - 改名避免冲突
  const barCategories = []
  tableData.value.forEach((item) => {
    const category = item[labelColumn] || ''
    if (!barCategories.includes(category)) {
      barCategories.push(category)
    }
  })

  // 系列数据
  const barSeries = []

  // 构建值列
  config.valueColumns.forEach((column, index) => {
    const seriesData = []

    // 为每个类别收集数据
    barCategories.forEach((category) => {
      const matchingItems = tableData.value.filter((item) => item[labelColumn] === category)
      let value = 0

      if (matchingItems.length > 0) {
        // 对于多个匹配项，使用求和
        value = matchingItems.reduce((sum, item) => {
          const itemValue = parseFloat(item[column.prop])
          return sum + (isNaN(itemValue) ? 0 : itemValue)
        }, 0)
      }

      seriesData.push(value)
    })

    barSeries.push({
      name: column.label || column.prop,
      type: 'bar',
      data: seriesData,
      barMaxWidth: 50, // 设置柱条最大宽度
      barGap: '30%', // 增加柱间距
      itemStyle: {
        color: getColorFromTheme(index),
        borderRadius: [4, 4, 0, 0], // 柱条顶部圆角
      },
      label: {
        show: userChartConfig.value.showDataLabels,
        position: 'top',
        formatter: '{c}',
      },
      emphasis: {
        focus: 'series', // 强调聚焦整个系列
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.3)',
        },
      },
      markLine:
        seriesData.length > 0
          ? {
              data: [{ type: 'average', name: '平均值' }],
              symbol: ['none', 'none'],
              label: {
                show: true,
                position: 'end',
              },
              lineStyle: {
                color: '#999',
                width: 1,
                type: 'dashed',
              },
            }
          : undefined,
      // 添加动画效果
      animationDelay: function (idx) {
        return idx * 50 + index * 100
      },
    })
  })

  // 初始化图例选中状态
  const barLegendSelected = {}
  barSeries.forEach((s) => {
    barLegendSelected[s.name] = true
  })

  const option = {
    ...baseOption,
    tooltip: {
      ...baseOption.tooltip,
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    legend: {
      ...baseOption.legend,
      show: userChartConfig.value.showLegend && barSeries.length > 1,
      orient:
        userChartConfig.value.legendPosition === 'left' ||
        userChartConfig.value.legendPosition === 'right'
          ? 'vertical'
          : 'horizontal',
      left:
        userChartConfig.value.legendPosition === 'right'
          ? 'right'
          : userChartConfig.value.legendPosition === 'left'
            ? 'left'
            : 'center',
      top: userChartConfig.value.legendPosition === 'bottom' ? 'bottom' : 'top',
      bottom: userChartConfig.value.legendPosition === 'bottom' ? 10 : undefined,
      selected: barLegendSelected,
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: userChartConfig.value.legendPosition === 'bottom' ? '15%' : '3%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: barCategories,
      axisTick: {
        alignWithLabel: true,
      },
      axisLabel: {
        interval: 0, // 强制显示所有标签
        rotate: barCategories.length > 10 ? 45 : 0, // 如果类别太多，旋转标签
        textStyle: {
          fontSize: 12,
        },
      },
    },
    yAxis: {
      type: 'value',
      splitLine: {
        lineStyle: {
          type: 'dashed',
        },
      },
    },
    dataZoom:
      barCategories.length > 10
        ? [
            {
              type: 'inside',
              start: 0,
              end: 100,
            },
            {
              type: 'slider',
              show: true,
              start: 0,
              end: 100,
            },
          ]
        : undefined,
    series: barSeries,
  }

  return option
}

// 构建折线图配置
const buildLineChartOption = (baseOption, config) => {
  // 折线图配置
  const labelColumn = config.labelColumn?.prop
  if (!labelColumn) return baseOption

  // 获取所有类别 - 改名避免冲突
  const lineCategories = []
  tableData.value.forEach((item) => {
    const category = item[labelColumn] || ''
    if (!lineCategories.includes(category)) {
      lineCategories.push(category)
    }
  })

  // 系列数据
  const lineSeries = []

  // 构建值列
  config.valueColumns.forEach((column, index) => {
    const seriesData = []

    // 为每个类别收集数据
    lineCategories.forEach((category) => {
      const matchingItems = tableData.value.filter((item) => item[labelColumn] === category)
      let value = 0

      if (matchingItems.length > 0) {
        // 对于多个匹配项，使用求和
        value = matchingItems.reduce((sum, item) => {
          const itemValue = parseFloat(item[column.prop])
          return sum + (isNaN(itemValue) ? 0 : itemValue)
        }, 0)
      }

      seriesData.push(value)
    })

    lineSeries.push({
      name: column.label || column.prop,
      type: 'line',
      data: seriesData,
      smooth: true, // 使用平滑曲线
      showSymbol: true, // 显示数据点
      symbolSize: 8, // 调整数据点大小
      lineStyle: {
        width: 3, // 调整线宽
        shadowColor: 'rgba(0,0,0,0.3)',
        shadowBlur: 10,
        shadowOffsetY: 5,
      },
      itemStyle: {
        color: getColorFromTheme(index),
        borderColor: '#fff',
        borderWidth: 2,
      },
      label: {
        show: userChartConfig.value.showDataLabels,
        position: 'top',
        formatter: '{c}',
      },
      emphasis: {
        focus: 'series', // 强调聚焦整个系列
        scale: true, // 高亮时数据点放大
        lineStyle: {
          width: 4, // 高亮时线条变粗
        },
      },
      areaStyle: {
        opacity: 0.2, // 添加半透明面积
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          {
            offset: 0,
            color: getColorFromTheme(index),
          },
          {
            offset: 1,
            color: 'rgba(255, 255, 255, 0.1)',
          },
        ]),
      },
      markLine:
        seriesData.length > 0
          ? {
              data: [{ type: 'average', name: '平均值' }],
              symbol: ['none', 'none'],
              label: {
                show: true,
                position: 'end',
              },
              lineStyle: {
                color: '#999',
                width: 1,
                type: 'dashed',
              },
            }
          : undefined,
      // 添加动画效果
      animationDelay: function (idx) {
        return idx * 50 + index * 100
      },
    })
  })

  // 初始化图例选中状态
  const lineLegendSelected = {}
  lineSeries.forEach((s) => {
    lineLegendSelected[s.name] = true
  })

  const option = {
    ...baseOption,
    tooltip: {
      ...baseOption.tooltip,
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985',
        },
      },
    },
    legend: {
      ...baseOption.legend,
      show: userChartConfig.value.showLegend && lineSeries.length > 1,
      orient:
        userChartConfig.value.legendPosition === 'left' ||
        userChartConfig.value.legendPosition === 'right'
          ? 'vertical'
          : 'horizontal',
      left:
        userChartConfig.value.legendPosition === 'right'
          ? 'right'
          : userChartConfig.value.legendPosition === 'left'
            ? 'left'
            : 'center',
      top: userChartConfig.value.legendPosition === 'bottom' ? 'bottom' : 'top',
      bottom: userChartConfig.value.legendPosition === 'bottom' ? 10 : undefined,
      selected: lineLegendSelected,
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: userChartConfig.value.legendPosition === 'bottom' ? '15%' : '3%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: lineCategories,
      boundaryGap: false, // 坐标轴两边不留白
      axisLabel: {
        interval: 0, // 强制显示所有标签
        rotate: lineCategories.length > 10 ? 45 : 0, // 如果类别太多，旋转标签
        textStyle: {
          fontSize: 12,
        },
      },
      axisPointer: {
        label: {
          show: true,
        },
      },
    },
    yAxis: {
      type: 'value',
      splitLine: {
        lineStyle: {
          type: 'dashed',
        },
      },
      scale: true, // 自动调整Y轴范围
    },
    dataZoom:
      lineCategories.length > 10
        ? [
            {
              type: 'inside',
              start: 0,
              end: 100,
            },
            {
              type: 'slider',
              show: true,
              start: 0,
              end: 100,
            },
          ]
        : undefined,
    series: lineSeries,
  }

  return option
}

// 导出功能实现
const handleExport = (command) => {
  if (command === 'csv') {
    exportToCSV()
  } else if (command === 'excel') {
    exportToExcel()
  } else if (command === 'image') {
    exportToImage()
  }
}

// 导出为CSV
const exportToCSV = () => {
  if (!tableData.value || tableData.value.length === 0) {
    return
  }

  const columnHeaders = props.columns.map((col) => col.label || col.prop).join(',')
  const rows = tableData.value.map((row) => {
    return props.columns
      .map((col) => {
        // 处理单元格中可能包含逗号的情况
        const cellValue = row[col.prop]
        if (cellValue === null || cellValue === undefined) return ''
        const cell = String(cellValue)
        return cell.includes(',') ? `"${cell}"` : cell
      })
      .join(',')
  })

  const csvContent = [columnHeaders, ...rows].join('\n')
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')

  // 创建下载链接
  link.href = URL.createObjectURL(blob)
  link.download = `${props.title || '数据导出'}.csv`
  link.style.display = 'none'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)

  // 触发导出事件
  emit('export-data', { type: 'csv', data: csvContent })
}

// 导出为Excel
const exportToExcel = () => {
  if (!tableData.value || tableData.value.length === 0) {
    return
  }

  // 创建工作簿
  const wb = XLSX.utils.book_new()

  // 准备数据
  const wsData = [
    // 表头
    props.columns.map((col) => col.label || col.prop),
    // 数据行
    ...tableData.value.map((row) =>
      props.columns.map((col) => (row[col.prop] !== undefined ? row[col.prop] : '')),
    ),
  ]

  // 创建工作表
  const ws = XLSX.utils.aoa_to_sheet(wsData)

  // 添加工作表到工作簿
  XLSX.utils.book_append_sheet(wb, ws, props.title || '数据')

  // 导出
  XLSX.writeFile(wb, `${props.title || '数据导出'}.xlsx`)

  // 触发导出事件
  emit('export-data', { type: 'excel', data: wb })
}

// 导出为图片
const exportToImage = () => {
  if (!chartInstance) return

  // 获取图表的base64图像
  const imageUrl = chartInstance.getDataURL({
    type: 'png',
    pixelRatio: 2, // 提高图片质量
    backgroundColor: '#fff',
    excludeComponents: ['toolbox'],
  })

  // 创建下载链接
  const link = document.createElement('a')
  link.href = imageUrl
  link.download = `${props.title || '图表导出'}.png`
  link.style.display = 'none'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)

  // 触发导出事件
  emit('export-data', { type: 'image', data: imageUrl })
}

// 保存为模板
const saveAsTemplate = () => {
  showTemplateDialog.value = true

  // 默认填充模板名称
  if (!templateForm.value.name) {
    templateForm.value.name = `${currentDisplayMode.value}图表 - ${new Date().toLocaleDateString()}`
  }
}

// 确认保存模板
const confirmSaveTemplate = () => {
  if (!templateForm.value.name) {
    return
  }

  const template = {
    name: templateForm.value.name,
    description: templateForm.value.description,
    type: currentDisplayMode.value,
    config: { ...userChartConfig.value },
    createTime: new Date().toISOString(),
  }

  // 触发保存模板事件
  emit('template-save', template)

  // 关闭对话框并重置表单
  showTemplateDialog.value = false
  templateForm.value = {
    name: '',
    description: '',
  }
}

// 应用自定义图表配置
const applyChartConfig = () => {
  // 不需要关闭配置区域
  // showChartConfig.value = false

  // 重新创建图表
  if (currentDisplayMode.value !== 'table') {
    nextTick(() => {
      createChart()
    })
  }
}

// 重置图表配置
const resetChartConfig = () => {
  // 重置为默认设置
  initUserConfig()

  // 应用配置
  applyChartConfig()
}

// 关闭图表配置面板
const closeChartConfig = () => {
  showChartConfig.value = false
}

// 表格行点击处理
const onRowClick = (row) => {
  emit('row-click', row)
}

// 组件挂载时初始化
onMounted(() => {
  console.log('组件挂载中，当前显示模式：', currentDisplayMode.value, '是否有数据：', hasData.value)

  // 窗口大小变化事件将在 createChart 中进行注册

  // 确保只有在有数据且非表格模式时才创建图表
  if (currentDisplayMode.value !== 'table' && hasData.value) {
    nextTick(() => {
      try {
        const analysis = dataAnalysis.value
        // 确保数据分析结果已经存在
        if (analysis && analysis.all && analysis.all.length > 0) {
          // 确保用户配置已经初始化
          if (!userChartConfig.value.labelColumn) {
            initUserConfig()
          }
          // 延迟一点创建图表，确保DOM已完全渲染
          setTimeout(() => {
            createChart()
          }, 300)
        } else {
          console.warn('数据分析结果无效')
        }
      } catch (err) {
        console.error('图表初始化失败:', err)
      }
    })
  } else {
    console.log('当前为表格模式或无数据，不创建图表')
  }
})

// 组件卸载时清理
onUnmounted(() => {
  // 移除窗口大小变化监听
  if (handleResize.current) {
    window.removeEventListener('resize', handleResize.current)
  }

  // 销毁图表实例
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
})

// 处理模式变更
const handleModeChange = (mode) => {
  currentDisplayMode.value = mode
}

// 获取模式显示名称
const getModeDisplayName = (mode) => {
  const names = {
    table: '表格',
    pie: '饼图',
    bar: '柱状图',
    line: '折线图',
  }
  return names[mode] || mode
}

// 自动应用推荐的显示模式
const autoApplyRecommendation = () => {
  if (props.enableSmartRecommendation && hasData.value) {
    const recommendation = getRecommendedDisplayMode.value
    if (currentDisplayMode.value !== recommendation.mode) {
      console.log(`智能推荐: ${recommendation.reason}`)
      currentDisplayMode.value = recommendation.mode
    }
  }
}

// 监听数据变化，自动应用推荐
watch(
  () => [hasData.value, dataAnalysis.value],
  () => {
    if (props.enableSmartRecommendation) {
      nextTick(() => {
        autoApplyRecommendation()
      })
    }
  },
  { immediate: true, deep: true },
)

// 监听强制表格模式变化，确保数据量超过100条时自动切换到表格模式
watch(
  isForceTableMode,
  (shouldForceTable) => {
    if (shouldForceTable && currentDisplayMode.value !== 'table') {
      console.log(`数据量超过100条(${tableData.value.length}行)，自动切换到表格模式`)
      currentDisplayMode.value = 'table'
    }
  },
  { immediate: true },
)
</script>

<style scoped>
.data-display-component {
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid var(--el-border-color-lighter);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.display-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.display-title-area {
  display: flex;
  align-items: center;
  gap: 10px;
}

.display-title {
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.display-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.option-icon {
  margin-right: 5px;
}

.filter-container {
  padding: 12px 16px;
  display: flex;
  align-items: center;
  gap: 12px;
  border-bottom: 1px solid var(--el-border-color-lighter);
  background-color: var(--el-fill-color-light);
}

.filter-actions {
  display: flex;
  gap: 8px;
}

.table-container {
  padding: 16px;
}

.chart-container {
  padding: 16px;
  position: relative;
  min-height: 450px;
}

.chart-container > div {
  width: 100%;
  height: 100%;
  min-height: 400px;
}

.no-data {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.8);
}

.chart-loading {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.5);
  z-index: 10;
}

.pagination-container {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

.config-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.config-header h4 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

:deep(.el-table) {
  --el-table-header-bg-color: var(--el-color-primary-light-9);
  --el-table-row-hover-bg-color: var(--el-color-primary-light-9);
}

.chart-config-form {
  padding: 16px;
}

.chart-config-form h4 {
  margin-top: 0;
  margin-bottom: 16px;
  font-size: 16px;
  color: var(--el-text-color-primary);
  border-bottom: 1px solid var(--el-border-color-lighter);
  padding-bottom: 8px;
}

.chart-actions {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 内联配置区域样式 */
.inline-chart-config {
  border-bottom: 1px solid var(--el-border-color-lighter);
  padding: 16px;
  transition: all 0.3s;
}

.data-detail {
  padding: 16px;
}

.detail-item {
  margin-bottom: 12px;
  border-bottom: 1px dashed var(--el-border-color-lighter);
  padding-bottom: 8px;
}

.detail-label {
  display: block;
  font-size: 14px;
  color: var(--el-text-color-secondary);
  margin-bottom: 4px;
}

.detail-value {
  font-size: 16px;
  color: var(--el-text-color-primary);
}

/* 深色模式适配 */
:global(.dark-mode) .data-display-component {
  border-color: var(--el-border-color-darker);
}

:global(.dark-mode) .display-controls {
  background-color: var(--el-bg-color-darker);
}

:global(.dark-mode) .inline-chart-config {
  background-color: var(--el-bg-color-darker);
}

:global(.dark-mode) .filter-container {
  background-color: var(--el-fill-color-darker);
}

/* 智能推荐样式 */
.mode-option {
  padding: 8px 0;
  min-width: 220px;
}

.mode-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}

.mode-name {
  flex: 1;
  font-weight: 500;
}

.mode-reason {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  line-height: 1.4;
  padding-left: 24px;
}

.recommended-option {
  background-color: var(--el-color-success-light-9);
}

.recommended-option .mode-header {
  color: var(--el-color-success-dark-2);
}

/* 推荐选项动画效果 */
.recommended-option {
  position: relative;
  overflow: hidden;
}

.recommended-option::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(
    90deg,
    transparent,
    rgba(var(--el-color-success-rgb), 0.1),
    transparent
  );
  transition: left 0.5s ease;
}

.recommended-option:hover::before {
  left: 100%;
}

/* 深色模式下的推荐样式 */
:global(.dark-mode) .recommended-option {
  background-color: rgba(var(--el-color-success-rgb), 0.1);
}

:global(.dark-mode) .mode-reason {
  color: var(--el-text-color-placeholder);
}
</style>
